package com.example.haojiutao.interceptor;

import com.alibaba.fastjson.JSON;
import com.example.haojiutao.common.Result;
import com.example.haojiutao.constant.CacheKeyConstant;
import com.example.haojiutao.constant.Enum.ExceptionCodeEnum;
import com.example.haojiutao.model.domain.User;
import com.example.haojiutao.utils.H5LoginUserUtil;
import com.example.haojiutao.utils.RedisUtil;
import jakarta.servlet.ServletContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.PrintWriter;

/**
 * @Description:
 * @Author: wang_meiying
 * @CreateTime: 2024/1/24 19:25
 */
@Slf4j
@Component
public class AuthLoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisUtil redisUtil;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{
        log.info("AuthLoginInterceptor.preHandle 拦截器已执行，请求地址：{}，请求方法：{}",request.getRequestURI(),request.getMethod());
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        //if(!(handler instanceof HandlerMethod)){//放行 OPTIONS
        if("OPTIONS".equals((request.getMethod()))){
            return true;
        }
        //由请求头中获取 token. auth-token
        String token = request.getHeader("auth-token");
        log.info("AuthLoginInterceptor.preHandle token: {}",token);
        if(StringUtils.hasLength(token)) { //token 不为空
            //根据 token 获取服务器保存的信息，判断当前 token 是否有效
            //ServletContext context = request.getServletContext();
            //Object obj = context.getAttribute(CacheKeyConstant.getTokenKey(token));
            Object obj = redisUtil.get(CacheKeyConstant.getTokenKey(token));
            if (null != obj) {//可以由服务器获取信息
                log.info("获取到内容：{}",obj);
                //将用户信息保存到线程中，供 Controller.Service 中读取
                H5LoginUserUtil.setLoginUser((User)obj);
                return true;
            }
        }
        PrintWriter writer = response.getWriter();
        writer.write(JSON.toJSONString(Result.faile(ExceptionCodeEnum.NO_LOGIN)));
        writer.close();
        return false;
    }
}